<template>
  <div class="bg-gray-50 min-h-screen">
    <!-- 页面标题 -->
    <div class="bg-white border-b border-gray-200 shadow-sm">
      <div class="container mx-auto px-4 py-5 flex justify-between items-center">
        <h1 class="text-2xl font-bold text-gray-800">媒体库</h1>
        <div class="flex items-center gap-3">
          <button 
            class="btn btn-primary flex items-center"
            @click="openUploadModal"
          >
            <i class="fa fa-upload mr-2"></i>
            <span>上传新文件</span>
          </button>
          <button 
            class="btn btn-secondary flex items-center"
            @click="handleBatchDelete"
            :disabled="selectedItems.length === 0"
          >
            <i class="fa fa-trash mr-2"></i>
            <span>批量删除</span>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 主内容区 -->
    <div class="container mx-auto px-4 py-6">
      <!-- 筛选和搜索区 -->
      <div class="bg-white rounded-lg shadow-sm p-5 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">文件类型</label>
            <select 
              v-model="filterFileType" 
              class="form-input w-full"
              @change="handleFilterChange"
            >
              <option value="">全部文件</option>
              <option value="image">图片</option>
              <option value="video">视频</option>
              <option value="document">文档</option>
            </select>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">文件分类</label>
            <select 
              v-model="filterCategory" 
              class="form-input w-full"
              @change="handleFilterChange"
            >
              <option value="">全部分类</option>
              <option value="banner">轮播图</option>
              <option value="product">产品图片</option>
              <option value="article">文章配图</option>
              <option value="avatar">头像</option>
              <option value="other">其他</option>
            </select>
          </div>
          
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1">搜索</label>
            <div class="relative">
              <input 
                type="text" 
                v-model="searchKeyword" 
                class="form-input pl-10 w-full"
                placeholder="搜索文件名..."
                @keyup.enter="handleSearch"
              >
              <i class="fa fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
            </div>
          </div>
        </div>
        
        <div class="mt-4 flex flex-wrap items-center justify-between gap-3">
          <div class="flex items-center gap-2">
            <span class="text-sm text-gray-500">排序方式：</span>
            <select 
              v-model="sortBy" 
              class="form-input"
              @change="handleFilterChange"
              style="width: auto;"
            >
              <option value="uploadTime_desc">最新上传</option>
              <option value="uploadTime_asc">最早上传</option>
              <option value="name_asc">名称（A-Z）</option>
              <option value="name_desc">名称（Z-A）</option>
              <option value="size_desc">大小（从大到小）</option>
              <option value="size_asc">大小（从小到大）</option>
            </select>
          </div>
          
          <div class="flex gap-3">
            <button 
              class="btn btn-secondary"
              @click="resetFilters"
            >
              <i class="fa fa-refresh mr-1"></i>重置筛选
            </button>
            <button 
              class="btn btn-primary"
              @click="handleSearch"
            >
              <i class="fa fa-search mr-1"></i>搜索
            </button>
          </div>
        </div>
      </div>
      
      <!-- 存储统计 -->
      <div class="bg-white rounded-lg shadow-sm p-5 mb-6">
        <div class="flex flex-wrap items-center justify-between gap-4">
          <div>
            <h3 class="text-lg font-medium text-gray-800">存储空间</h3>
            <p class="text-sm text-gray-500 mt-1">总容量：10GB，已使用：{{ usedStorageGB }}GB ({{ usedStoragePercent }}%)</p>
          </div>
          <div class="w-full md:w-2/3 bg-gray-200 rounded-full h-2.5">
            <div 
              class="bg-primary h-2.5 rounded-full transition-all duration-500 ease-out"
              :style="{ width: usedStoragePercent + '%' }"
            ></div>
          </div>
          <div class="grid grid-cols-2 md:grid-cols-4 gap-4 w-full md:w-auto">
            <div class="text-center">
              <p class="text-sm text-gray-500">文件总数</p>
              <p class="text-xl font-bold">{{ totalFilesCount }}</p>
            </div>
            <div class="text-center">
              <p class="text-sm text-gray-500">图片</p>
              <p class="text-xl font-bold">{{ imageFilesCount }}</p>
            </div>
            <div class="text-center">
              <p class="text-sm text-gray-500">视频</p>
              <p class="text-xl font-bold">{{ videoFilesCount }}</p>
            </div>
            <div class="text-center">
              <p class="text-sm text-gray-500">文档</p>
              <p class="text-xl font-bold">{{ documentFilesCount }}</p>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 视图切换和批量选择 -->
      <div class="flex flex-wrap items-center justify-between mb-4 gap-3">
        <div class="flex items-center">
          <button 
            class="p-2 rounded border border-gray-300 text-gray-500 hover:bg-gray-50"
            @click="selectAll = !selectAll"
          >
            <i class="fa" :class="selectAll ? 'fa-check-square-o' : 'fa-square-o'"></i>
            <span class="ml-1 text-sm">{{ selectAll ? '取消全选' : '全选' }}</span>
          </button>
          <span class="ml-3 text-sm text-gray-500">已选择 {{ selectedItems.length }} 个文件</span>
        </div>
        
        <div class="flex items-center gap-2">
          <span class="text-sm text-gray-500">视图：</span>
          <button 
            class="p-2 rounded border border-gray-300"
            :class="viewMode === 'grid' ? 'bg-gray-100' : 'hover:bg-gray-50'"
            @click="viewMode = 'grid'"
          >
            <i class="fa fa-th-large"></i>
          </button>
          <button 
            class="p-2 rounded border border-gray-300"
            :class="viewMode === 'list' ? 'bg-gray-100' : 'hover:bg-gray-50'"
            @click="viewMode = 'list'"
          >
            <i class="fa fa-list"></i>
          </button>
          <span class="text-sm text-gray-500 ml-3">每页显示：</span>
          <select 
            v-model="pageSize" 
            class="form-input"
            @change="handlePageSizeChange"
            style="width: auto;"
          >
            <option value="12">12</option>
            <option value="24">24</option>
            <option value="48">48</option>
            <option value="96">96</option>
          </select>
        </div>
      </div>
      
      <!-- 媒体文件列表 - 网格视图 -->
      <div 
        v-if="viewMode === 'grid'"
        class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4 mb-6"
      >
        <div 
          v-for="file in filteredFiles" 
          :key="file.id"
          class="group relative bg-white rounded-lg shadow-sm overflow-hidden border border-gray-200 hover:border-primary transition-all"
        >
          <div class="aspect-square bg-gray-50 relative">
            <!-- 文件预览 -->
            <div class="w-full h-full flex items-center justify-center p-2">
              <img 
                v-if="file.type === 'image'" 
                :src="file.url" 
                :alt="file.name"
                class="w-full h-full object-contain"
              >
              <i v-if="file.type === 'video'" class="fa fa-file-video-o text-5xl text-gray-400"></i>
              <i v-if="file.type === 'document'" class="fa fa-file-text-o text-5xl text-gray-400"></i>
            </div>
            
            <!-- 选择框 -->
            <div class="absolute top-2 left-2 z-10">
              <input 
                type="checkbox" 
                class="form-checkbox text-primary rounded"
                v-model="selectedItems"
                :value="file.id"
              >
            </div>
            
            <!-- 悬停操作按钮 -->
            <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-50 transition-colors flex items-center justify-center opacity-0 group-hover:opacity-100">
              <div class="flex gap-2">
                <button 
                  class="w-8 h-8 rounded-full bg-white flex items-center justify-center text-gray-700 hover:text-primary"
                  @click.stop="handlePreview(file)"
                  title="预览"
                >
                  <i class="fa fa-eye"></i>
                </button>
                <button 
                  class="w-8 h-8 rounded-full bg-white flex items-center justify-center text-gray-700 hover:text-primary"
                  @click.stop="handleEdit(file)"
                  title="编辑信息"
                >
                  <i class="fa fa-pencil"></i>
                </button>
                <button 
                  class="w-8 h-8 rounded-full bg-white flex items-center justify-center text-gray-700 hover:text-red-500"
                  @click.stop="handleDelete(file)"
                  title="删除"
                >
                  <i class="fa fa-trash"></i>
                </button>
              </div>
            </div>
          </div>
          
          <!-- 文件信息 -->
          <div class="p-3">
            <div class="text-sm font-medium text-gray-900 truncate" title="{{ file.name }}">{{ file.name }}</div>
            <div class="flex items-center justify-between mt-1">
              <span class="text-xs text-gray-500">{{ formatFileSize(file.size) }}</span>
              <span class="text-xs text-gray-500">{{ formatDate(file.uploadTime) }}</span>
            </div>
            <div class="mt-2">
              <span 
                class="inline-block px-2 py-0.5 text-xs rounded-full bg-gray-100 text-gray-800"
              >
                {{ getCategoryName(file.category) }}
              </span>
            </div>
          </div>
        </div>
        
        <!-- 无数据状态 -->
        <div v-if="filteredFiles.length === 0 && !loading" class="col-span-full text-center py-16">
          <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
            <i class="fa fa-file-o text-2xl text-gray-400"></i>
          </div>
          <h3 class="text-lg font-medium mb-2">暂无文件</h3>
          <p class="text-gray-500 max-w-md mx-auto">
            没有找到符合当前条件的文件，请尝试调整筛选条件或上传新文件
          </p>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="loading" class="col-span-full text-center py-16">
          <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
            <i class="fa fa-spinner fa-spin text-2xl text-gray-400"></i>
          </div>
          <p class="text-gray-500">加载中...</p>
        </div>
      </div>
      
      <!-- 媒体文件列表 - 列表视图 -->
      <div v-if="viewMode === 'list'" class="bg-white rounded-lg shadow-sm overflow-hidden mb-6">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-12">
                <input 
                  type="checkbox" 
                  class="form-checkbox text-primary rounded"
                  v-model="selectAll"
                >
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                预览
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                文件名
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                类型
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                分类
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                大小
              </th>
              <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                上传时间
              </th>
              <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作
              </th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="file in filteredFiles" :key="file.id" class="hover:bg-gray-50 transition-colors">
              <td class="px-6 py-4 whitespace-nowrap">
                <input 
                  type="checkbox" 
                  class="form-checkbox text-primary rounded"
                  v-model="selectedItems"
                  :value="file.id"
                >
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="w-12 h-12 bg-gray-50 flex items-center justify-center">
                  <img 
                    v-if="file.type === 'image'" 
                    :src="file.url" 
                    :alt="file.name"
                    class="w-full h-full object-cover"
                  >
                  <i v-if="file.type === 'video'" class="fa fa-file-video-o text-xl text-gray-400"></i>
                  <i v-if="file.type === 'document'" class="fa fa-file-text-o text-xl text-gray-400"></i>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900">{{ file.name }}</div>
                <div class="text-xs text-gray-500">{{ file.url }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="text-sm text-gray-500">
                  {{ file.type === 'image' ? '图片' : file.type === 'video' ? '视频' : '文档' }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span 
                  class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800"
                >
                  {{ getCategoryName(file.category) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ formatFileSize(file.size) }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                {{ formatDate(file.uploadTime) }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                <button 
                  class="text-primary hover:text-primary/80 mr-3"
                  @click="handlePreview(file)"
                >
                  预览
                </button>
                <button 
                  class="text-gray-600 hover:text-gray-900 mr-3"
                  @click="handleEdit(file)"
                >
                  编辑
                </button>
                <button 
                  class="text-red-600 hover:text-red-900"
                  @click="handleDelete(file)"
                >
                  删除
                </button>
              </td>
            </tr>
            
            <!-- 无数据状态 -->
            <tr v-if="filteredFiles.length === 0 && !loading">
              <td colspan="8" class="px-6 py-12 text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                  <i class="fa fa-file-o text-2xl text-gray-400"></i>
                </div>
                <h3 class="text-lg font-medium mb-2">暂无文件</h3>
                <p class="text-gray-500 max-w-md mx-auto">
                  没有找到符合当前条件的文件，请尝试调整筛选条件或上传新文件
                </p>
              </td>
            </tr>
            
            <!-- 加载状态 -->
            <tr v-if="loading">
              <td colspan="8" class="px-6 py-12 text-center">
                <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
                  <i class="fa fa-spinner fa-spin text-2xl text-gray-400"></i>
                </div>
                <p class="text-gray-500">加载中...</p>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页 -->
      <div v-if="filteredFiles.length > 0 && !loading" class="px-6 py-4 flex items-center justify-between">
        <div class="text-sm text-gray-500">
          显示 {{ (currentPage - 1) * pageSize + 1 }} 到 {{ Math.min(currentPage * pageSize, totalFilesCount) }} 个，共 {{ totalFilesCount }} 个文件
        </div>
        
        <div class="flex items-center gap-2">
          <button 
            class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 text-gray-500 hover:bg-gray-50 disabled:opacity-50"
            :disabled="currentPage === 1"
            @click="currentPage = currentPage - 1"
          >
            <i class="fa fa-chevron-left text-xs"></i>
          </button>
          
          <button 
            v-for="page in visiblePages" 
            :key="page"
            class="w-8 h-8 flex items-center justify-center rounded"
            :class="currentPage === page ? 'bg-primary text-white' : 'border border-gray-300 hover:bg-gray-50'"
            @click="currentPage = page"
          >
            {{ page }}
          </button>
          
          <button 
            class="w-8 h-8 flex items-center justify-center rounded border border-gray-300 text-gray-500 hover:bg-gray-50 disabled:opacity-50"
            :disabled="currentPage === totalPages"
            @click="currentPage = currentPage + 1"
          >
            <i class="fa fa-chevron-right text-xs"></i>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 上传文件弹窗 -->
    <UploadFileDialog 
      :visible="uploadModalVisible"
      @close="uploadModalVisible = false"
      @upload-success="handleUploadSuccess"
    />
    
    <!-- 预览弹窗 -->
    <PreviewDialog 
      :visible="previewVisible"
      :file="previewFile"
      @close="previewVisible = false"
    />
    
    <!-- 编辑文件信息弹窗 -->
    <EditFileInfoDialog 
      :visible="editVisible"
      :file="fileToEdit"
      @close="editVisible = false"
      @save="handleFileInfoSave"
    />
    
    <!-- 确认删除弹窗 -->
    <ConfirmDialog 
      :visible="deleteConfirmVisible"
      title="确认删除"
      :content="`确定要删除选中的 ${deleteCount} 个文件吗？此操作不可撤销。`"
      @confirm="confirmDelete"
      @cancel="deleteConfirmVisible = false"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import UploadFileDialog from './components/UploadFileDialog.vue'
import PreviewDialog from './components/PreviewDialog.vue'
import EditFileInfoDialog from './components/EditFileInfoDialog.vue'
import ConfirmDialog from '@/components/ConfirmDialog.vue'

// 状态管理
const filterFileType = ref('')
const filterCategory = ref('')
const searchKeyword = ref('')
const sortBy = ref('uploadTime_desc')
const currentPage = ref(1)
const pageSize = ref(12)
const viewMode = ref('grid')
const selectAll = ref(false)
const loading = ref(false)

// 文件数据
const mediaFiles = ref([])
const selectedItems = ref([])
const totalFilesCount = ref(0)
const imageFilesCount = ref(0)
const videoFilesCount = ref(0)
const documentFilesCount = ref(0)
const usedStorageGB = ref(0)
const usedStoragePercent = ref(0)

// 弹窗状态
const uploadModalVisible = ref(false)
const previewVisible = ref(false)
const editVisible = ref(false)
const deleteConfirmVisible = ref(false)
const previewFile = ref(null)
const fileToEdit = ref(null)
const filesToDelete = ref([])
const deleteCount = ref(0)

// 初始化页面数据
onMounted(() => {
  fetchMediaFiles()
  fetchStorageStatistics()
})

// 获取媒体文件列表
const fetchMediaFiles = async () => {
  loading.value = true
  try {
    // 模拟API请求
    const mockData = Array.from({ length: 36 }, (_, i) => {
      // 随机文件类型
      const types = ['image', 'image', 'image', 'video', 'document']
      const type = types[Math.floor(Math.random() * types.length)]
      
      // 随机分类
      const categories = ['banner', 'product', 'article', 'avatar', 'other']
      const category = categories[Math.floor(Math.random() * categories.length)]
      
      // 随机大小 (KB)
      const size = Math.floor(Math.random() * 10240) + 100
      
      // 随机日期
      const daysAgo = Math.floor(Math.random() * 30)
      const date = new Date()
      date.setDate(date.getDate() - daysAgo)
      
      return {
        id: i + 1,
        name: `${category}-${i + 1}.${type === 'image' ? 'jpg' : type === 'video' ? 'mp4' : 'pdf'}`,
        type,
        category,
        size,
        url: type === 'image' ? `https://picsum.photos/id/${i + 100}/400/400` : '',
        uploadTime: date.toISOString(),
        uploadBy: 'admin'
      }
    })
    
    mediaFiles.value = mockData
    totalFilesCount.value = mockData.length
    imageFilesCount.value = mockData.filter(f => f.type === 'image').length
    videoFilesCount.value = mockData.filter(f => f.type === 'video').length
    documentFilesCount.value = mockData.filter(f => f.type === 'document').length
    
    loading.value = false
  } catch (error) {
    console.error('获取媒体文件失败:', error)
    loading.value = false
  }
}

// 获取存储统计
const fetchStorageStatistics = async () => {
  try {
    // 模拟API请求
    const totalSizeKB = mediaFiles.value.reduce((sum, file) => sum + file.size, 0)
    const totalSizeGB = (totalSizeKB / 1024 / 1024).toFixed(2)
    usedStorageGB.value = totalSizeGB
    usedStoragePercent.value = Math.min(Math.round((totalSizeGB / 10) * 100), 100)
  } catch (error) {
    console.error('获取存储统计失败:', error)
  }
}

// 筛选后的文件
const filteredFiles = computed(() => {
  let result = [...mediaFiles.value]
  
  // 类型筛选
  if (filterFileType.value) {
    result = result.filter(file => file.type === filterFileType.value)
  }
  
  // 分类筛选
  if (filterCategory.value) {
    result = result.filter(file => file.category === filterCategory.value)
  }
  
  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(file => 
      file.name.toLowerCase().includes(keyword)
    )
  }
  
  // 排序
  result.sort((a, b) => {
    const [field, order] = sortBy.value.split('_')
    let valueA, valueB
    
    if (field === 'uploadTime') {
      valueA = new Date(a.uploadTime).getTime()
      valueB = new Date(b.uploadTime).getTime()
    } else if (field === 'name') {
      valueA = a.name.toLowerCase()
      valueB = b.name.toLowerCase()
    } else if (field === 'size') {
      valueA = a.size
      valueB = b.size
    }
    
    return order === 'desc' ? valueB - valueA : valueA - valueB
  })
  
  // 分页
  const startIndex = (currentPage.value - 1) * pageSize.value
  return result.slice(startIndex, startIndex + pageSize.value)
})

// 总页数
const totalPages = computed(() => {
  return Math.ceil(totalFilesCount.value / pageSize.value) || 1
})

// 可见页码
const visiblePages = computed(() => {
  const pages = []
  const maxVisible = 5
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisible / 2))
  const endPage = Math.min(totalPages.value, startPage + maxVisible - 1)
  
  if (endPage - startPage + 1 < maxVisible) {
    startPage = Math.max(1, endPage - maxVisible + 1)
  }
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i)
  }
  
  return pages
})

// 处理筛选条件变化
const handleFilterChange = () => {
  currentPage.value = 1
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置筛选条件
const resetFilters = () => {
  filterFileType.value = ''
  filterCategory.value = ''
  searchKeyword.value = ''
  sortBy.value = 'uploadTime_desc'
  currentPage.value = 1
}

// 处理页面大小变化
const handlePageSizeChange = () => {
  currentPage.value = 1
}

// 处理全选
watch(selectAll, (newVal) => {
  if (newVal) {
    // 全选当前页文件
    selectedItems.value = filteredFiles.value.map(file => file.id)
  } else {
    // 取消全选
    selectedItems.value = []
  }
})

// 处理文件上传成功
const handleUploadSuccess = (newFiles) => {
  // 添加新上传的文件到列表
  newFiles.forEach(file => {
    mediaFiles.value.unshift({
      ...file,
      id: Math.max(...mediaFiles.value.map(f => f.id), 0) + 1
    })
  })
  
  // 更新统计数据
  totalFilesCount.value += newFiles.length
  newFiles.forEach(file => {
    if (file.type === 'image') imageFilesCount.value++
    else if (file.type === 'video') videoFilesCount.value++
    else if (file.type === 'document') documentFilesCount.value++
  })
  
  fetchStorageStatistics()
}

// 打开上传弹窗
const openUploadModal = () => {
  uploadModalVisible.value = true
}

// 处理预览
const handlePreview = (file) => {
  previewFile.value = file
  previewVisible.value = true
}

// 处理编辑
const handleEdit = (file) => {
  fileToEdit.value = { ...file }
  editVisible.value = true
}

// 保存文件信息
const handleFileInfoSave = (updatedFile) => {
  const index = mediaFiles.value.findIndex(file => file.id === updatedFile.id)
  if (index !== -1) {
    mediaFiles.value.splice(index, 1, updatedFile)
  }
  editVisible.value = false
}

// 处理删除
const handleDelete = (file) => {
  filesToDelete.value = [file.id]
  deleteCount.value = 1
  deleteConfirmVisible.value = true
}

// 处理批量删除
const handleBatchDelete = () => {
  if (selectedItems.value.length === 0) return
  
  filesToDelete.value = [...selectedItems.value]
  deleteCount.value = selectedItems.value.length
  deleteConfirmVisible.value = true
}

// 确认删除
const confirmDelete = () => {
  if (filesToDelete.value.length === 0) return
  
  // 执行删除操作
  mediaFiles.value = mediaFiles.value.filter(
    file => !filesToDelete.value.includes(file.id)
  )
  
  // 更新统计数据
  totalFilesCount.value = mediaFiles.value.length
  imageFilesCount.value = mediaFiles.value.filter(f => f.type === 'image').length
  videoFilesCount.value = mediaFiles.value.filter(f => f.type === 'video').length
  documentFilesCount.value = mediaFiles.value.filter(f => f.type === 'document').length
  
  // 清空选中
  selectedItems.value = []
  selectAll.value = false
  
  // 更新存储统计
  fetchStorageStatistics()
  
  deleteConfirmVisible.value = false
}

// 格式化文件大小
const formatFileSize = (sizeKB) => {
  if (sizeKB >= 1024) {
    return (sizeKB / 1024).toFixed(2) + ' MB'
  }
  return sizeKB + ' KB'
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取分类名称
const getCategoryName = (category) => {
  const categoryMap = {
    'banner': '轮播图',
    'product': '产品图片',
    'article': '文章配图',
    'avatar': '头像',
    'other': '其他'
  }
  return categoryMap[category] || category
}
</script>
    